<template>
  <a-modal
    title="选择部门"
    width="30%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin tip="Loading..." :spinning="false">
      <a-input-search style="margin-bottom: 1px" placeholder="请输入部门名称按回车进行搜索" @search="onSearch" />
      <a-tree
        style="height: 500px;overflow-y: auto"
        checkable
        :treeData="treeData"
        :checkStrictly="true"
        @check="onCheck"
        @select="onSelect"
        @expand="onExpand"
        :autoExpandParent="autoExpandParent"
        :expandedKeys="expandedKeys"
        :checkedKeys="checkedKeys">
      </a-tree>

    </a-spin>
  </a-modal>
</template>

<script>
import { fetchList } from '@/api/sys/dept'
import { treeDataTranslate } from '@/utils/util'
export default {
  name: 'DeptSelectModal',
  props: ['multi', 'departId'],
  data () {
    return {
      visible: false,
      confirmLoading: false,
      rootOpened: true,
      treeData: [],
      autoExpandParent: true,
      expandedKeys: [],
      dataList: [],
      checkedKeys: [],
      checkedRows: [],
      searchValue: ''
    }
  },
  mounted () {
    this.loadDepart()
  },
  watch: {
    departId () {
      this.initDepartComponent()
    },
    visible: {
      handler () {
        if (this.departId) {
          this.checkedKeys = this.departId
        } else {
          this.checkedKeys = []
        }
      }
    }
  },
  methods: {
    // 初始化
    show () {
      this.visible = true
      this.checkedRows = []
      this.checkedKeys = []
    },
    // 获取部门信息
    loadDepart () {
      fetchList().then(res => {
        const record = res.data
        // 转换格式
        this.treeData = treeDataTranslate(record, 'deptId', 'name')
        this.reWriterWithSlot(record)
        this.initDepartComponent()
        if (this.rootOpened) {
          this.initExpandedKeys(record)
        }
      })
    },
    // 获取 部门名称，传给父组件
    initDepartComponent () {
      let names = ''
      if (this.departId) {
        // 转换为 JSON 字符串
        const currDepartId = this.departId
        // 将部门名封装成字符串
        for (const item of this.dataList) {
          if (currDepartId.indexOf(item.deptId) >= 0) {
            names += ',' + item.name
          }
        }
        if (names) {
          // 如果names不为空，则字符串第一个为','，因此我们在字符串下标为一处开始取
          names = names.substring(1)
        }
      }
      this.$emit('initComp', names)
    },
    // 获取dataList
    reWriterWithSlot (record) {
      for (const item of record) {
        if (item.children && item.children.length > 0) {
          this.reWriterWithSlot(item.children)
          // 复制对象
          const temp = Object.assign({}, item)
          temp.children = {}
          this.dataList.push(temp)
        } else {
          this.dataList.push(item)
          item.scopedSlots = { title: 'title' }
        }
      }
    },
    // 获取（受控）展开指定的树节点
    initExpandedKeys (arr) {
      if (arr && arr.length > 0) {
        const keys = []
        for (const item of arr) {
          if (item.children && item.children.length > 0) {
            keys.push(item.deptId)
          }
        }
        this.expandedKeys = [...keys]
      } else {
        this.expandedKeys = []
      }
    },
    onCheck (checkedKeys, info) {
      if (!this.multi) {
        const arr = checkedKeys.checked.filter(item => this.checkedKeys.indexOf(item) < 0)
        this.checkedKeys = [...arr]
        this.checkedRows = (this.checkedKeys.length === 0) ? [] : [info.node.dataRef]
      } else {
        this.checkedKeys = checkedKeys.checked
        this.checkedRows = this.getCheckedRows(this.checkedKeys)
      }
    },
    onSelect (selectedKeys, info) {
      const keys = []
      keys.push(selectedKeys[0])
      if (!this.checkedKeys || this.checkedKeys.length === 0 || !this.multi) {
        this.checkedKeys = [...keys]
        this.checkedRows = [info.node.dataRef]
      } else {
        const currKey = info.node.dataRef.key
        if (this.checkedKeys.indexOf(currKey) >= 0) {
          this.checkedKeys = this.checkedKeys.filter(item => item !== currKey)
        } else {
          this.checkedKeys.push(...keys)
        }
      }
      this.checkedRows = this.getCheckedRows(this.checkedKeys)
    },

    // 控制节点打开/关闭
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    // 点击确认
    handleSubmit () {
      if (!this.checkedKeys || this.checkedKeys.length === 0) {
        this.$emit('ok', '')
      } else {
        this.$emit('ok', this.checkedRows, this.checkedKeys)
      }
      this.handleCancel()
    },
    // 关闭
    handleCancel () {
      this.visible = false
      this.checkedKeys = []
    },

    getParentKey (currKey, treeData) {
      let parentKey
      for (let i = 0; i < treeData.length; i++) {
        const node = treeData[i]
        if (node.children) {
          if (node.children.some(item => item.key === currKey)) {
            parentKey = node.key
          } else if (this.getParentKey(currKey, node.children)) {
            parentKey = this.getParentKey(currKey, node.children)
          }
        }
      }
      return parentKey
    },
    // 进行搜索
    onSearch (value) {
      const expandedKeys = this.dataList.map((item) => {
        item.name = JSON.stringify(item.name)
        if (item.name.indexOf(value) > -1) {
          return this.getParentKey(item.deptId, this.treeData)
        }
        return null
      }).filter((item, i, self) => item && self.indexOf(item) === i)

      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    },
    // 根据 checkedKeys 获取 rows
    getCheckedRows (checkedKeys) {
      const forChildren = (list, key) => {
        for (const item of list) {
          if (item.key === key) {
            return item
          }
          if (item.children instanceof Array) {
            const value = forChildren(item.children, key)
            if (value != null) {
              return value
            }
          }
        }
        return null
      }

      const rows = []
      for (const key of checkedKeys) {
        const row = forChildren(this.treeData, key)
        if (row != null) {
          rows.push(row)
        }
      }
      return rows
    }
  }
}

</script>

<style scoped>

</style>
